<template>
	<el-form ref="formRef" :inline="false" :model="form" :rules="rules" :label-width="options.labelWidth">
		<el-row>
			<el-col :span="options.span" v-for="item in options.list" :key="item">
				<el-form-item :label="item.label" :prop="item.prop">
					<!-- 文本框、数字框、下拉框、日期框、开关、上传, 地址选择器， radio框, 输入数字框 -->
					<el-input v-if="item.type === 'input'" v-model="form[item.prop]" :disabled="item.disabled"
						:placeholder="item.placeholder" clearable></el-input>
					<el-input type="textarea" v-if="item.type === 'textarea'" v-model="form[item.prop]" :disabled="item.disabled" :rows="item.rows"
						:placeholder="item.placeholder" clearable></el-input>
					<el-input-number v-else-if="item.type === 'number'" v-model="form[item.prop]"
						:disabled="item.disabled" controls-position="right"></el-input-number>
					<el-select v-else-if="item.type === 'select'" :filterable="true" v-model="form[item.prop]" :disabled="item.disabled"
						:placeholder="item.placeholder" clearable>
						<el-option v-for="opt in item.opts" :label="opt[item.labelItem || 'label']" :value="opt[item.valueItem || 'value']" :key="opt[item.valueItem || 'value']"></el-option>
					</el-select>
					<el-select v-else-if="item.type === 'cabinet'" :filterable="true" v-model="form[item.prop]" :disabled="item.disabled"
						:placeholder="item.placeholder" @change="cabinetParams" clearable>
						<el-option v-for="opt in item.opts" :label="opt[item.labelItem || 'label']" :value="opt[item.valueItem || 'value']" :key="opt[item.valueItem || 'value']"></el-option>
					</el-select>
					<el-cascader v-if="item.type === 'custom_area'" :filterable="true" @change="choose_area" v-model="form[item.prop]" v-bind:options="pcaTextArr" :placeholder="item.placeholder" size="large" clearable/>
					<el-date-picker v-else-if="item.type === 'date'" type="date" v-model="form[item.prop]"
						:value-format="item.format"></el-date-picker>
					<el-switch v-else-if="item.type === 'switch'" v-model="form[item.prop]"
						:active-value="item.activeValue" :inactive-value="item.inactiveValue"
						:active-text="item.activeText" :inactive-text="item.inactiveText"></el-switch>
					<el-radio-group v-else-if="item.type === 'radio'" v-model="form[item.prop]">
							<el-radio v-for="opt in item.opts" :value="opt.value" :key="opt.value">{{opt.label}}</el-radio>
					</el-radio-group>
					<el-input-number :min="1" v-else-if="item.type === 'input-num'" v-model="form[item.prop]" />

					<el-text type="warning" v-else-if="item.tips">{{ item.tips }}</el-text>
					<el-upload :data='item.typeData' 
					v-else-if="item.type === 'upload'" 
					class="avatar-uploader"
					:headers="{token: token}"
					:action='domain.fetchUrl + "/share_glasses_manager_api/public_fun/upload_file"'
					:show-file-list="false" 
					:on-success="handleAvatarSuccess" 
					:before-upload="beforeAvatarUpload">
						<img v-if="form.thumb" :src="form.thumb" class="avatar" />
						<img v-else-if="form[item.prop]" :src="form[item.prop]" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
					<slot :name="item.prop" v-else>

					</slot>
				</el-form-item>
			</el-col>
		</el-row>

		<el-form-item>
			<el-button type="primary" @click="saveEdit(formRef)" :loading="loadingState.$state.loading">保 存</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { FormOption } from '@/types/form-option';
import { FormInstance, FormRules, UploadProps, ElMessage } from 'element-plus';
import { PropType, ref } from 'vue';
import { pcaTextArr } from "element-china-area-data";
import { fatchDataState } from '../store/fetchData';
import domain from '@/utils/domain.js';

const loadingState = fatchDataState()

const token = ref('')
token.value = localStorage.getItem('token')

console.log(loadingState.$state.loading)

const { options, formData, edit, update, chooseArea, getImgUrl, changeCabinetParams } = defineProps({
	options: {
		type: Object as PropType<FormOption>,
		required: true
	},
	formData: {
		type: Object,
		required: true
	},
	edit: {
		type: Boolean,
		required: false
	},
	update: {
		type: Function,
		required: true
	},
	chooseArea: {
		type: Function,
		required: false
	},
	changeCabinetParams: {
		type: Function,
		required: false
	},
	getImgUrl: {
		type: Function,
		required: false
	}
});

const form = ref({ ...(edit ? formData : {}) });

const choose_area = (val) => {
	chooseArea(form.value, val)
}

const cabinetParams = (val) => {
	changeCabinetParams(form.value, val)
}

const rules: FormRules = options.list.map(item => {
	if (item.required) {
		return { [item.prop]: [{ required: true, message: `${item.label}不能为空`, trigger: 'blur' }] };
	}
	return {};
}).reduce((acc, cur) => ({ ...acc, ...cur }), {});


const formRef = ref<FormInstance>();
const saveEdit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(valid => {
		if (!valid) return false;
		loadingState.handleChangeState(true)
		update(form.value);
	});
};

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
	form.value.thumb = URL.createObjectURL(uploadFile.raw!);
	getImgUrl(form.value, response.data)
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持png和jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('大小限制2MB!')
    return false
  }
  return true
}

</script>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
.avatar  {
	width: 100%;
	height: 100%
}
</style>
